#include "stdafx.h"
#include "net/URIStreamFactory.hpp"
#include "net/URI.hpp"
#include "stdlib/bugcheck.hpp"
#include "stdlib/exception.hpp"
using namespace JHCPP::stdlib;
using namespace JHCPP::stdlib::jhException;
#include "filesys/file.hpp"
using JHCPP::filesys::CFile;
#include "stream/FileStream.hpp"
using JHCPP::stream::CFileInputStream;

#include <algorithm>

NET_NAMESPACE_BEGIN

CURIStreamFactory::CURIStreamFactory()
{
}

CURIStreamFactory::~CURIStreamFactory()
{
}


CURIRedirection::CURIRedirection(const std::string& uri) : m_uri(uri)
{
}

CURIRedirection::CURIRedirection(const CURIRedirection& redir) : m_uri(redir.m_uri)
{
}

CURIRedirection& CURIRedirection::operator = (const CURIRedirection& redir)
{
	CURIRedirection tmp(redir);
	swap(tmp);
	return *this;
}

void CURIRedirection::swap(CURIRedirection& redir)
{
	std::swap(m_uri, redir.m_uri);
}

const std::string& CURIRedirection::uri() const
{
	return m_uri;
}


CFileStreamFactory::CFileStreamFactory()
{
}

CFileStreamFactory::~CFileStreamFactory()
{
}

std::istream* CFileStreamFactory::open(const CURI& uri)
{
	jh_assert (uri.isRelative() || uri.getScheme() == "file");

	std::string uriPath = uri.getPath();
	if (uriPath.substr(0, 2) == "./")
		uriPath.erase(0, 2);
	CPath p(uriPath, CPath::PATH_LUNIX);
	p.setNode(uri.getHost());
	return open(p);
}

std::istream* CFileStreamFactory::open(const CPath& path)
{
	CFile file(path);
	if (!file.exists()) throw FileNotFoundException(path.toString());

	CFileInputStream* istr = new CFileInputStream(path.toString(), std::ios::binary);
	if (!istr->good())
	{
		delete istr;
		throw OpenFileException(path.toString());
	}	
	return istr;
}

NET_NAMESPACE_END
